//
//  InformationViewController.m
//  myCar
//
//  Created by 刘莉 on 14-10-27.
//  Copyright (c) 2014年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "InformationViewController.h"
#import "AutoScrollView.h"
#import "IndexCollectionViewCell.h"
#import "Information.h"

#import "NewsViewController.h"
#import "WebViewController.h"
#import "PhotoViewController.h"
#import "MBProgressHUD.h"
#import "WebColor.h"
#import "AFNetworking.h"

@interface InformationViewController ()<UICollectionViewDataSource, UICollectionViewDelegate,CLLocationManagerDelegate, UIAlertViewDelegate>
@property (nonatomic, retain) CLGeocoder *geocoder;
@property(nonatomic , retain)CLLocationManager *LocationManager;
@property(nonatomic , assign)CLLocationCoordinate2D mylocation;
@property(nonatomic, retain)MKMapView *mapView;
@property(nonatomic, retain)MKPinAnnotationView *
annotation;
@property (nonatomic, retain)NSMutableArray *informationArr;
@property (nonatomic, retain)NSMutableArray *imageArr;
@property (nonatomic, retain)NSMutableArray *indexImageArr;
@property (nonatomic, retain)NSMutableArray *imgInfo;
@property (nonatomic, retain)UICollectionView *collectionView;
@property (nonatomic, retain)AutoScrollView *autoScrollView;
@property (nonatomic, retain)NSString *cityName;
@property (nonatomic, retain)NSString *proName;
@property (nonatomic, retain)UIScrollView *scrollView;
@property (nonatomic, retain)UILabel *titleLabel;
@end

@implementation InformationViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.informationArr = [NSMutableArray array];
        self.imageArr = [NSMutableArray array];
        self.indexImageArr = [NSMutableArray array];
        self.imgInfo = [NSMutableArray array];
        
        
    }
    return self;
}

- (void)dealloc
{
    [_imgInfo release];
    [_informationArr release];
    [_imageArr release];
    [_indexImageArr release];
    [super dealloc];
}


- (void)viewDidLoad
{
    // Do any additional setup after loading the view.
    [super viewDidLoad];
    [self setTitlelabel];
    self.view.backgroundColor = [WebColor whiteSmoke];
    
    if (self.cityName == nil) {
        [self locate];
    }
    NSDictionary *attributes=[NSDictionary dictionaryWithObjectsAndKeys:[WebColor honeydew],NSForegroundColorAttributeName,[UIFont boldSystemFontOfSize:20],NSFontAttributeName, nil];
    [self.navigationController.navigationBar setTitleTextAttributes:attributes];
    
    [self reloadData];
    [self initView];
}

- (void)reloadData
{
    // 网络请求
    MBProgressHUD *hub = [[MBProgressHUD alloc] initWithView:self.view];
    [hub setMode:MBProgressHUDModeIndeterminate];
    [self.view addSubview:hub];
    [hub show:YES];
    NSString *imgStr = @"http://mrobot.pcauto.com.cn/v2/cms/channels/1?pageNo=1&pageSize=20&v=4.0.0";
        AFHTTPRequestOperationManager *manager1 = [AFHTTPRequestOperationManager manager];
        [manager1.responseSerializer setAcceptableContentTypes: [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css", nil]];
       [manager1 GET:imgStr parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
           for (NSDictionary *dic in [responseObject objectForKey:@"focus"]) {
               [self.imageArr addObject:[dic valueForKey:@"image"]];
               Information *info = [[Information alloc] init];
               info.image = [dic valueForKey:@"image"];
               info.url = [dic valueForKey:@"url"];
               info.title = [dic valueForKey:@"title"];
               [self.imgInfo addObject:info];
               [info release];
           }
           [self.autoScrollView setImageUrls:self.imageArr];
             [hub removeFromSuperview];
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            
            NSMutableArray *arr = [NSMutableArray array];
            for (int i = 0; i < 6 ; i++) {
                NSString *str = @"zanwu.jpg" ;
                [arr addObject:str];
            }
           self.autoScrollView.imageNames = arr;
        }];
   
    
}

- (void)setTitlelabel
{
    self.titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 44)];
    self.titleLabel.textAlignment = 1;
    self.titleLabel.textColor = [WebColor white];
    [self.titleLabel setFont:[UIFont fontWithName:@"Helvetica-Bold" size:20]];
    self.titleLabel.backgroundColor = [WebColor dodgerBlue];
    self.titleLabel.text = @"爱尚汽车网";
    [self.navigationController.navigationBar addSubview:self.titleLabel];
    [_titleLabel release];
}

- (void)initView
{
    for (int i = 0; i < 13; i++) {
        NSString *str = [NSString stringWithFormat:@"index%d.png", i];
        [self.indexImageArr addObject:str];
    }
    // scrollerView
    self.scrollView = [[UIScrollView alloc] initWithFrame:self.view.bounds];
    
    [self.view addSubview:self.scrollView];
    
    self.scrollView.contentOffset = CGPointMake(0, 0);
    
    
    // 到达边缘后没有滑动效果
    self.scrollView.bounces = NO;
    // 首页轮播图片
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.autoScrollView = [[AutoScrollView alloc]initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width , 180) ];
    // 图片自动轮播的时间间隔
    self.autoScrollView.timeInterval = 5;
    [self.autoScrollView setTarget:self action:@selector(tapAction)];
    [self.scrollView addSubview:self.autoScrollView];
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    // 调整cell的大小
    flowLayout.itemSize = CGSizeMake(106, 100);
    // 调整滚动方向
    flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    // cell之间的间距
    flowLayout.minimumInteritemSpacing = 1;
    // cell行之间的间距
    flowLayout.minimumLineSpacing = 1;
    // 整个section区域的布局 距离边界的距离(上, 左, 下, 右)
    // flowLayout.sectionInset = UIEdgeInsetsMake(20, 40, 20, 40);
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, self.autoScrollView.frame.size.height + self.autoScrollView.frame.origin.y, 320, 505) collectionViewLayout:flowLayout];
    self.collectionView.backgroundColor = [UIColor whiteColor];
    // 禁用collectionView的滚动效果
    self.collectionView.scrollEnabled = NO;
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [self.scrollView addSubview:self.collectionView];
    [self.collectionView registerClass:[IndexCollectionViewCell class] forCellWithReuseIdentifier:@"reuse"];
    [_collectionView release];
    
    [_autoScrollView release];
    
    // 设定scrollerView的滚动范围
    self.scrollView.contentSize = CGSizeMake(0, self.collectionView.frame.origin.y + self.collectionView.frame.size.height + 50 + 64);
    [_scrollView release];
}

- (void)setBackItem:(NSString *)str
{
    UIBarButtonItem *backItem = [[[UIBarButtonItem alloc] init] autorelease];
    backItem.title = str;
    self.navigationItem.backBarButtonItem = backItem;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.informationArr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    IndexCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];
    Information *info = [self.informationArr objectAtIndex:indexPath.item];
    cell.info = info;
    NSString *str = [self.indexImageArr objectAtIndex:indexPath.item];
    NSLog(@"*******%@", str);
    cell.myImageView.image = [UIImage imageNamed:str];
    cell.backgroundColor = [WebColor whiteSmoke];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    Information *info = [self.informationArr objectAtIndex:indexPath.item];
    // 如果点击的图赏页 推出图赏的视图控制器
    if ([info.title isEqualToString:@"图赏"]) {
        PhotoViewController *photoVC = [[PhotoViewController alloc] init];
        photoVC.info = info;
        [self setBackItem:info.title];
        [self.navigationController pushViewController:photoVC animated:YES];
        [photoVC release];
        
    }
    else {
        NewsViewController *news = [[NewsViewController alloc] init];
        news.info = info;
        [self setBackItem:info.title];
        NSString *str = [self.cityName substringToIndex:self.cityName.length - 1];
        NSString *str1 = [self.proName substringToIndex:self.proName.length - 1];
        news.proName = str1;
        news.buttonTitle = str;
        [self.navigationController pushViewController:news animated:YES];
        [news release];
    }
}


- (void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBar.backgroundColor = [WebColor white];
    self.titleLabel.hidden = NO;
    self.navigationController.navigationBar.translucent = NO;
    NSString *filePath = [[NSBundle mainBundle]pathForResource:@"local" ofType:@"txt"];
    NSString*fileString = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
    NSArray *lines = [fileString componentsSeparatedByString:@"\n"];
    for (NSString *str in lines) {
        NSArray *tempArr = [str componentsSeparatedByString:@","];
        Information *info = [[Information alloc] init];
        info.number = tempArr[0];
        info.title = tempArr[1];
        [self.informationArr addObject:info];
        [self.indexImageArr addObject:tempArr[2]];
        [info release];
    }
    
}

- (void)viewWillDisappear:(BOOL)animated
{
    self.titleLabel.hidden = YES;
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"navbackground.jpg"] forBarMetrics:UIBarMetricsDefault];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)tapAction
{
    // NSLog(@"点击");
    WebViewController *webVC = [[WebViewController alloc] init];
    if (self.imgInfo.count != 0) {
        Information *info = [self.imgInfo objectAtIndex:self.autoScrollView.pageNo];
        webVC.info = info;
        [self.navigationController pushViewController: webVC animated:YES];
        [webVC release];
    } else {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"对不起" message:@"网络未连接" delegate:self cancelButtonTitle:@"请返回" otherButtonTitles:nil, nil];
        [alertView show];
        [alertView release];
    }
}
#pragma mark locate
- (void)locate
{
    if ([CLLocationManager locationServicesEnabled]) {
        self.LocationManager = [[CLLocationManager alloc]init];
        self.LocationManager.delegate = self;
        //选择定位的方式为最优的状态.
        self.LocationManager.desiredAccuracy = kCLLocationAccuracyBest;
        //出发事件的最小距离
        self.LocationManager.distanceFilter = 1.0f;
        [self.LocationManager startUpdatingLocation];
        [_LocationManager release];
    }
}



-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    static int m = 0;
    
    CLLocation *currentLocation = [locations lastObject];
    self.mylocation = currentLocation.coordinate;
    self.geocoder = [[CLGeocoder alloc] init];
    [self.geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error) {
        if (error == nil && [placemarks count] > 0) {
            if (m == 0)
            {
                m++;
                for (CLPlacemark *placeMark in placemarks) {
                    NSDictionary *test = [placeMark addressDictionary];
                    //  Country(国家)  State(城市)  SubLocality(区)
                    static int i = 1;
                    NSLog(@"&&&&&&&&&&&&%d", i++);
                    NSLog(@"%@",[test objectForKey:@"Country"]);
                    NSLog(@"%@", [test objectForKey:@"State"]);
                    NSLog(@"%@", [test objectForKey:@"City"]);
                    self.cityName = [test objectForKey:@"City"];
                    self.proName = [test objectForKey:@"State"];
                    NSLog(@"%@", [test objectForKey:@"Street"]);
                    
                }
            }
        }
    }];
    [_geocoder release];
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
